package frame.m.com.mylibrary.http;



import com.orhanobut.logger.Logger;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import frame.m.com.mylibrary.BuildConfig;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Administrator on 2017/7/6.
 */

public class RetrofitUtil<T> {
    private static final int DEFAULT_TIMEOUT = 5;
    private static final String BASE_URL = "http://192.168.1.103:8080";

    private T service;

    public T getAPI(Class<T> cls) {
            if (service == null) {
                service = new Retrofit.Builder()
                        .client(procideOkhttpClient())
                        .addConverterFactory(GsonConverterFactory.create())
                        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                        .baseUrl(BASE_URL)
                        .build()
                    .create(cls);
        }
        return service;
    }

    /**
     * 获取okhttp的client
     *
     * @return
     */
    public static OkHttpClient procideOkhttpClient() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
//        设置http的日志打印
        if (true) {
            HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
            httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            builder.addNetworkInterceptor(httpLoggingInterceptor);
        }
        /**
         * 为所有请求添加请求头
         */
        builder.addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request();
                Logger.d(request);
                Response response = chain.proceed(request);
                return response;
            }
        });
        return builder.build();
    }

}
